import React, { PureComponent, Fragment } from 'react';
import {
  Row,
  Card,
  Col,
  Form,
  Button,
  Input,
  DatePicker,
  Table,
  Select,
  Icon,
  Divider,
  Popconfirm,
  Modal,
  message,
  Alert,
} from 'antd';
import moment from 'moment';
import { getAuthority } from '@/utils/authority';
import RenderAuthorized from '@/components/Authorized';
import { baseUrl } from '../../services/baseUrl';
const Authorized = RenderAuthorized(getAuthority());
import { connect } from 'dva';
import router from 'umi/router';
import ProjectContactAdd from './components/ProjectContact/ProjectContactAdd';
import ProjectContactEdit from './components/ProjectContact/ProjectContactEdit';
import ProjectContactApprove from './components/ProjectContact/ProjectContactApprove';
import Ellipsis from '@/components/Ellipsis';
// 样式
import styles from './Repair.less';
const FormItem = Form.Item;
const Option = Select.Option;

const months = [
  { nodeName: 1, key: 1 },
  { nodeName: 2, key: 2 },
  { nodeName: 3, key: 3 },
  { nodeName: 4, key: 4 },
  { nodeName: 5, key: 5 },
  { nodeName: 6, key: 6 },
  { nodeName: 7, key: 7 },
  { nodeName: 8, key: 8 },
  { nodeName: 9, key: 9 },
  { nodeName: 10, key: 10 },
  { nodeName: 11, key: 11 },
  { nodeName: 12, key: 12 },
];
const currentYear = new Date().getFullYear();
const years = [
  { nodeName: currentYear, key: currentYear },
  { nodeName: currentYear - 1, key: currentYear - 1 },
  { nodeName: currentYear - 2, key: currentYear - 2 },
  { nodeName: currentYear - 3, key: currentYear - 3 },
];
@Form.create()
@connect(({ ProjectContact, loading, global, assessment }) => ({
  currentUrl: global.currentUrl,
  elementAuth: global.elementAuth,
  listAndTotal: ProjectContact.listAndTotal,
  companyList: assessment.companyList,
  loading: loading.effects['ProjectContact/fetchList'],
}))
export default class Repair extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      pageindex: 1,
      record:null
    };

    this.dispatch = this.props.dispatch;
  }
  returnColumn = () => {
    return [
      {
        title: '序号',
        width: 60,
        dataIndex: 'Id',
        render: (text, record, index) => `${index + 1}`,
        width: 50,
      },
      {
        title: '年份',
        dataIndex: 'nf',
        key: 'nf',
        width: 50,
      },
      {
        title: '月份',
        dataIndex: 'yf',
        key: 'yf',
        width: 50,
      },
      {
        title: '编号',
        dataIndex: 'bh',
        key: 'bh',
        width: 100,
      },
      {
        title: '工程名称',
        dataIndex: 'gcmc',
        key: 'gcmc',
        width: 200,
      },
      {
        title: '施工单位名称',
        dataIndex: 'sgdwmc',
        key: 'sgdwmc',
        width: 200,
      },
      {
        title: '抄送单位名称1',
        dataIndex: 'csdwmc',
        key: 'csdwmc',
        width: 80,
      },
      {
        title: '抄送单位名称2',
        dataIndex: 'csdwmc2',
        key: 'csdwmc2',
        width: 80,
      },
      {
        title: '联系提要',
        dataIndex: 'lxty',
        key: 'lxty',
        width: 200,
      },
      {
        title: '是否审批',
        dataIndex: 'spzt',
        key: 'spzt',
        width: 80,
        render: (text, record) => {
          if (text == null) return <span>未审批</span>;
          else return <span>已审批</span>;
        },
      },
      {
        title: '操作',
        key: 'action',
        width: 180,
        render: (text, record) => {
          return (
            <>
              <Authorized authority={this.props.elementAuth['check']}>
                <a
                  href="javascrips:;"
                  onClick={() => {
                    router.push({ pathname: `/municipal/projectcontact/details`, state: record });
                  }}
                >
                  <Icon type="profile" />
                  查看
                </a>
                <Divider type="vertical" />
              </Authorized>
              {!record.spzt&&<Authorized authority={this.props.elementAuth['approve']}>
                <a
                  href="javascrips:;"
                  onClick={() => {
                    this.setState({ record: record },()=>{
                      this['ApproveForm'].setState({ visible: true });
                    });
                  }}
                >
                  <Icon type="profile" />
                  审批
                </a>
                <Divider type="vertical" />
              </Authorized>}

              <Authorized authority={this.props.elementAuth['export']}>
                <a
                  href="javascrips:;"
                  onClick={() => {
                    window.open(`${baseUrl}/ProjectContactList/ExportToExcel/${record.id}`);
                  }}
                >
                  <Icon type="export" />
                  导出
                </a>
                <Divider type="vertical" />
              </Authorized>
              {record.spzt == 2 && <Authorized authority={this.props.elementAuth['edit']}>
                <a href="javascrips:;" onClick={this.handleEdit.bind(this, record)}>
                  <Icon type="edit" />
                  编辑
                </a>
                <Divider type="vertical" />
              </Authorized>}

              {record.spzt == 1 &&  <Authorized authority={this.props.elementAuth['editRollBack']}>
                <a
                  href="javascrips:;"
                  onClick={() => {
                    this.changeStatus({ id: record.id, status: 2 });
                  }}
                >
                  <Icon type="rollback" />
                  退回编辑
                </a>
                <Divider type="vertical" />
              </Authorized>}

              <Authorized authority={this.props.elementAuth['delete']}>
                <Popconfirm title="确定删除?" onConfirm={this.handleDelete.bind(this, record)}>
                  <a href="javascript:;">
                    <Icon type="delete" />
                    删除
                  </a>
                </Popconfirm>
              </Authorized>
            </>
          );
        },
      },
    ];
  };
  handleDelete = record => {
    const hide = message.loading('正在删除...', 0);
    this.dispatch({
      type: 'ProjectContact/fetchProjectContactDelete',
      payload: { id: record.id },
      callback: response => {
        hide();
        if (response.status) {
          message.success('删除成功');
        } else {
          message.error('删除失败');
          console.log(response.ErrorMessage);
        }
        this.fetchList();
      },
    });
  };
  changeStatus = ({ id = null, status = null } = {}) => {
    const hide = message.loading('正在修改...', 0);
    this.dispatch({
        type: 'emergency/fetchProjectContactCommitStatus',
        payload: {
            id: id,
        },
        callback: response => {
            hide();
            if (response.status) {
                message.success('修改成功');
                this.onPaginationChange(this.state.pageindex);
            } else {
                message.error('修改失败');
                message.error(response.ErrorMessage);
            }
        },
    });
};
  handleEdit = record => {
    this['EditForm'].setState({ visible: true });
    this.props.dispatch({
      type: 'ProjectContact/fetchSaveRecord',
      payload: record,
    });
  };
  queryList = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.fetchList({
          company: values.company,
          year: values.year,
          month: values.month,
          projectname: values.projectname,
        });
      }
    });
  };
  fetchGetCompany = () => {
    this.props.dispatch({
      type: 'assessment/fetchGetCompany',
      payload: {
        type: '养护维修',
      },
      callback: response => {
        message.error.error('养护单位获取失败');
        console.log(response);
      },
    });
  };
  fetchList = ({
    pagesize = 10,
    pageindex = 1,
    company = null,
    year = null,
    month = null,
    projectname = null,
  } = {}) => {
    this.props.dispatch({
      type: 'ProjectContact/fetchList',
      payload: {
        pagesize: pagesize,
        pageindex: pageindex,
        company: company,
        year: year,
        month: month,
        projectname: projectname,
      },
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取设施清单失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };
  resetData = () => {
    this.props.form.resetFields();
    this.fetchList();
  };
  OnRef = ({ ref = null, type = null } = {}) => {
    this[type] = ref;
  };
  getAuth = () => {
    const { dispatch, currentUrl, match } = this.props;
    dispatch({
      type: 'global/fetchUrl',
      payload: match.url,
      callback: response => {},
    });
    dispatch({
      type: 'global/fetchAuthorityElements',
      payload: { url: match.url },
    });
  };
  onPaginationChange = page => {
    const values = this.props.form.getFieldsValue();
    this.setState({ pageindex: page });
    this.fetchList({
      pageindex: page,
      company: values.company,
      year: values.year,
      month: values.month,
      projectname: values.projectname,
    });
  };
  componentDidMount = () => {
    !this.props.listAndTotal && this.fetchList();
    !this.props.companyList && this.fetchGetCompany();
    this.getAuth();
  };
  render() {
    const { loading, listAndTotal, companyList, elementAuth } = this.props;
    const { getFieldDecorator } = this.props.form;
    const pagination = {
      // size:'large',
      total: listAndTotal && listAndTotal.total && listAndTotal.total,
      onChange: this.onPaginationChange,
      current: this.state.pageindex,
      showTotal: (total, range) => `第${range[0]}条至${range[1]}条 | 总计${total}条记录数据 `,
    };
    return (
      <>
        <Card style={{ margin: '10px' }}>
          <Form layout="inline">
            <FormItem label="养护单位">
              {getFieldDecorator('company', { initialValue: null })(
                <Select style={{ width: '200px' }}>
                  {companyList &&
                    companyList.map(item => (
                      <Option key={item.Id} value={item.Id}>
                        {item.Name}
                      </Option>
                    ))}
                </Select>
              )}
            </FormItem>
            <FormItem label="年份">
              {getFieldDecorator('year', { initialValue: null })(
                <Select style={{ width: '200px' }}>
                  {years.length > 0
                    ? years.map(item => (
                        <Option key={item.key} value={item.key}>
                          {item.nodeName}
                        </Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>

            <FormItem label="月份">
              {getFieldDecorator('month', {
                initialValue: null,
              })(
                <Select style={{ width: '200px' }}>
                  {months.length > 0
                    ? months.map(item => (
                        <Option key={item.key} value={item.key}>
                          {item.nodeName}月
                        </Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>
            <FormItem label="工程名称">
              {getFieldDecorator('projectname', {
                initialValue: null,
              })(<Input />)}
            </FormItem>

            <FormItem>
              <Button type="primary" onClick={this.queryList}>
                查询
              </Button>
            </FormItem>

            <FormItem>
              <Button onClick={this.resetData}>重置</Button>
            </FormItem>
            <Authorized authority={elementAuth['add']}>
              <FormItem>
                <Button
                  type="primary"
                  onClick={() => {
                    this.AddForm.setState({ visible: true });
                  }}
                >
                  新增
                </Button>
              </FormItem>
            </Authorized>
          </Form>
        </Card>
        <Card
          title={
            <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
              工程联系单清单
            </span>
          }
          style={{ margin: '10px' }}
        >
          <Table
            className={styles.RepairTable}
            size="small"
            align={'center'}
            loading={loading}
            bordered
            pagination={pagination}
            dataSource={listAndTotal && listAndTotal.data}
            columns={this.returnColumn()}
          />
          <ProjectContactAdd OnRef={this.OnRef} fetchList={this.fetchList} />
          <ProjectContactEdit OnRef={this.OnRef} fetchList={this.fetchList} />
          <ProjectContactApprove  OnRef={this.OnRef} fetchList={()=>{this.onPaginationChange(this.state.pageindex)}} record={this.state.record}/>
        </Card>
      </>
    );
  }
}
